package com.gin.no_gay_alliance.manager;


import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.manager.provider.VersionProvider;
import com.gin.no_gay_alliance.utils.DataStoreUtils;
import com.gin.no_gay_alliance.viewmodel.AppRelease;

import java.util.List;
import java.util.Locale;

/**
 * 升级管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/10 23:38
 **/
public class UpgradeManager {
    private static final String TAG = UpgradeManager.class.getSimpleName();
    /**
     * dataStore 使用的key，表示用户忽略更新的release id号
     */
    private static final String DATA_STORE_KEY_IGNORE_RELEASE_ID = "UPGRADE_ID";

    public void checkUpgrade(Context context) {
        // 获取release数据
        new VersionProvider(1, 10).async(false, data -> {
            if (!ObjectUtils.isEmpty(data)) {
                // 检查第一条数据与当前版本是否相同
                AppRelease release = data.get(0);
                if (!MyApplication.getVersionName().equals(release.tagName) && release.id > getIgnoreRelease()) {
                    // 如果不同，且该版本id大于忽略版本id，弹窗提示更新
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("发现新版本");
                    builder.setMessage(String.format(Locale.CHINA, "是否下载版本: %s %s", release.tagName, release.preRelease ? "[预览版]" : ""));
                    builder.setPositiveButton(R.string.confirm, (dialog, which) -> downloadRelease(release));
                    builder.setNegativeButton(R.string.cancel, null);
                    builder.setNeutralButton("忽略", (dialog, which) -> setIgnoreRelease(release.id));
                    MyApplication.app.handler.post(builder::show);
                } else {
                    Log.d(TAG, "checkUpgrade: 没有新版本");
                }
            }
        });
    }

    /**
     * 下载 release
     *
     * @param release release
     */
    public void downloadRelease(AppRelease release) {
        List<String> urls = release.findUrls();
        if (urls.isEmpty()) {
            MyApplication.app.handler.toast("该版本没有下载地址");
            return;
        }
        String url = urls.get(0);

        StringBuilder sb = new StringBuilder("no_gay_alliance_v");
        sb.append(release.tagName);
        if (release.preRelease) {
            sb.append("_pre");
        }
        sb.append("_release.apk");

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, sb.toString());
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager downloadManager = (DownloadManager) MyApplication.app.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.enqueue(request);
        MyApplication.app.handler.toast("开始下载");
    }

    /**
     * 获取忽略的版本id
     *
     * @return 忽略的版本id
     */
    public int getIgnoreRelease() {
        return DataStoreUtils.getInstance().get(DATA_STORE_KEY_IGNORE_RELEASE_ID, 0);
    }

    /**
     * 忽略一个版本id，小于等于该id的release版本不再提示自动更新
     *
     * @param id id
     */
    public void setIgnoreRelease(int id) {
        Log.d(TAG, "忽略Release版本: " + id);
        MyApplication.app.handler.toast("已忽略该版本");
        DataStoreUtils.getInstance().set(DATA_STORE_KEY_IGNORE_RELEASE_ID, id);
    }
}
